<template>
  <div style="padding-top: 40px; padding-bottom: 50px; background-color: #fff">
    <div style="text-align: center; margin-bottom: 20px">
      <p>
        注：以下所有上传资料均需加盖公章，支持图片格式JPG、PNG，且每个文件大小不超过{{
          imageSize
        }}M
      </p>
    </div>
    <a-form
      @submit="handleSubmit"
      style="
        margin-top: 8px;
        width: 80%;
        margin: 0 auto;
        background-color: #fff;
      "
      :form="form"
    >
      <a-form-item v-bind="formItemLayout" label="客户名称">
        <div>
          <a-select
            showSearch
            :notFoundContent="null"
            :defaultActiveFirstOption="false"
            :filterOption="false"
            @search="NameSearch"
            class="width-sty"
            :disabled="disabled"
            v-decorator="[
              'merchantMemberNo',
              { rules: [{ required: true, message: '请选择客户名称' }] },
            ]"
            placeholder="请选择客户名称"
          >
            <a-select-option v-for="d in seloptions" :key="d.merchantMemberNo">
              <div @click="handleChange1(d)">{{ d.merchantName }}</div>
            </a-select-option>
          </a-select>
        </div>
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="SN设备号">
        <a-input
          class="w-sty"
          v-decorator="[
            'snCode',
            { rules: [{ required: true, message: '请填写SN设备号' }] },
          ]"
          placeholder="请填写SN设备号"
          @change="snCodeChange"
          @blur="DeviceNumberBlur"
        />
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="终端类型">
        <span v-if="terminal.type == 'minipos'">电签pos</span>
        <span v-if="terminal.type == 'mpos'">mpos</span>
        <span v-if="terminal.type == 'epos'">智能pos</span>
        <span v-if="terminal.type == 'pos'">传统pos</span>
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="终端品牌">
        <span>{{ terminal.factoryName }}</span>
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="终端型号">
        <span>{{ terminal.modelName }}</span>
      </a-form-item>

      <a-form-item
        v-if="issmall == false"
        v-bind="formItemLayout"
        label="装机地址-所属地区"
      >
        <a-cascader
          :disabled="dobusDisabled"
          class="w-sty"
          v-decorator="['dobusAddress', { rules: [{required:true, message: '所属地区' }] }]"
          :options="options"
          notFoundContent="Not found"
          placeholder="请选择所属地区"
          @change="onChange"
        />
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="详细地址">
        <a-textarea
          class="w-sty"
          v-decorator="[
            'address',
            { rules: [{ required: true, message: '请输入详细地址' }] },
          ]"
          placeholder="请输入详细地址"
          :rows="2"
        />
        <p>
          <a @click="toSame">同实际经营地址</a>
        </p>
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="装机联系人">
        <a-input
          class="w-sty"
          v-decorator="[
            'contactName',
            { rules: [{ required: true, message: '请填写装机联系人' }] },
          ]"
          placeholder="请填写装机联系人"
        />
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="联系电话">
        <a-input
          class="w-sty"
          v-decorator="[
            'contactPhone',
            {
              rules: [
                { required: true, message: '请输入联系电话!' },
                { validator: validateCode },
              ],
              validateTrigger: 'blur',
            },
          ]"
          placeholder="请输入联系电话"
        />
      </a-form-item>

      <!-- <a-form-item style="margin-bottom: 0;" v-bind="formItemLayout" label="设备照片" help>
        <div class="clearfix" style="display:inline-block;">
          <a-upload v-decorator="['upload11',{rules: [{ required: true, message: '请上传设备照片!' }]}]" name="upfile"
            action="/file/file/upload" listType="picture-card" :fileList="fileList" :data="{to}"
            @preview="handlePreview" @change="handleChange">
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">设备照片</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </a-form-item>-->
      <!-- 其他材料 -->

      <a-form-item v-bind="formItemLayout" label="其他材料">
        <div class="clearfix">
          <a-upload
            v-decorator="['upload12']"
            name="upfile"
            :headers="henderstoken"
            action="/file/file/upload"
            listType="picture-card"
            :fileList="fileList2"
            :data="{ to }"
            @preview="handlePreview2"
            @change="handleChange2"
          >
            <div v-if="fileList2.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">其他材料</div>
            </div>
          </a-upload>
          <a-modal
            :visible="previewVisible2"
            :footer="null"
            @cancel="handleCancel2"
          >
            <img alt="example" style="width: 100%" :src="previewImage2" />
          </a-modal>
        </div>
        <a class="a-sty" @click="getFileDownload('add_terminal_ticket')"
          >增单机下载</a
        >
      </a-form-item>
      <a-modal :visible="success" :footer="null" @cancel="successCancel">
        <div style="text-align: center; color: green; font-size: 7vw">
          <a-icon type="check-circle" />
        </div>
        <div style="text-align: center;center;margin-top:15px">
          <h2>提交成功</h2>
        </div>
        <div style="margin-top: 15px">
          我们将在1-2个工作日内完成审核，可以前往“终端审核查询”查看进度
        </div>
        <div style="text-align: center; margin-top: 15px">
          <a-button @click="goterminalQuery">确定</a-button>
        </div>
      </a-modal>
      <a-col :xs="{ span: 24 }" :sm="{ span: 14, offset: 10 }">
        <a-form-item>
          <a-button
            class="submitButton"
            :loading="loading"
            html-type="submit"
            type="primary"
          >
            <span v-if="ismdf == false">提交</span>
            <span v-if="ismdf == true">提交修改</span>
          </a-button>
        </a-form-item>
      </a-col>
    </a-form>
  </div>
</template>
<script>
import { mapState, mapMutations, mapAction } from "vuex";
import api from "@/common/api";
export default {
  data() {
    return {
      typeDisabled: false,
      form: this.$form.createForm(this),
      terminal: {
        snCode: "",
        merchantMemberNo: "",
        factoryCode: "",
        factoryName: "----",
        modelCode: "",
        modelName: "---",
        type: "----",
        name: "",
        address: "",
        city: "",
        cityName: "",
        province: "",
        provinceName: "",
        county: "",
        countyName: "",
        contactName: "",
        contactPhone: "",
        facilityImg: "",
        otherImg: "",
      },
      provinceItem: "",
      cityItem: "",
      districtItem: "",
      henderstoken: {
        Authorization: localStorage.getItem("token"),
      },
      to:
        sessionStorage.getItem("memberNo") +
        "_" +
        sessionStorage.getItem("username"),
      fileList: [],
      merchantMemberNo: "",
      previewImage: "",
      previewVisible: false,
      fileList2: [],
      previewImage2: "",
      previewVisible2: false,
      success: false,
      dobusDisabled: false,
      disabled: false,
      loading:false,
      seloptions: [],
      ModificationData: {},
      ismdf: false,
      issmall: false,
      queryDetail: {
        merchantPosp: {},
      },
      options: [
        
      ],
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 9 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 14, offset: 1 },
          md: { span: 12, offset: 1 },
        },
      },
    };
  },
  props: {
    id: String, // 当一个页面有多个密码输入框时，用id来区分
    default: "1",
  },
  computed: {
    ...mapState({
      imageSize: (state) => state.imageSize,
    }),
  },
  beforeCreate() {},
  mounted() {
    this.NameSearch();
    if (this.$route.query.memberNo) {
      this.getQueryDetail(this.$route.query.memberNo);
      this.disabled = true;
    }
    if (this.$route.params.ModificationData) {
      this.ModificationData = this.$route.params.ModificationData;
      this.disabled = true;
      this.merchantMemberNo = this.ModificationData.merchantMemberNo;
      console.log("this.ModificationData", this.ModificationData);
      this.ismdf = true;
      this.init();
    }
    this.getareaData()
  },
  methods: {
    init() {
      setTimeout(() => {
        this.form.setFieldsValue({
          merchantMemberNo: this.ModificationData.merchantMemberNo,
          snCode: this.ModificationData.sncode,
          address: this.ModificationData.address,
          contactName: this.ModificationData.contactName,
          contactPhone: this.ModificationData.contactPhone,
          // upload11: this.ModificationData.facilityImg,
          upload12: this.ModificationData.otherImg,
        });
      }, 0);
      this.terminal.type = this.ModificationData.terminalType;
      this.terminal.factoryName = this.ModificationData.factoryName;
      this.terminal.modelName = this.ModificationData.modelName;
      this.terminal.facilityImg = this.ModificationData.facilityImg;
      if (this.ModificationData.otherImg) {
        this.terminal.otherImg = this.ModificationData.otherImg;
        this.fileList2 = [
          {
            uid: Math.random(10000),
            name: "xxx.png",
            status: "done",
            url: "/file/file/download/" + this.terminal.otherImg,
          },
        ];
      }
      // this.fileList = [
      //   {
      //     uid: Math.random(10000),
      //     name: "xxx.png",
      //     status: "done",
      //     url: "/file/file/download/" + this.terminal.facilityImg
      //   }
      // ];
    },
    onChange(value, selectedOptions) {
      console.log("changevalue", typeof value, value);
      console.log("selectedOptions", selectedOptions);
      this.text = value;
      // this.text = selectedOptions.map(o => o.label);
      // if (selectedOptions.length == 1) {

      // }
      // if (selectedOptions.length == 2) {

      // }
      if (selectedOptions.length == 3) {
        this.provinceItem = {
          label: selectedOptions[0].label,
          value: selectedOptions[0].value,
        };
        this.cityItem = {
          label: selectedOptions[1].label,
          value: selectedOptions[1].value,
        };
        this.districtItem = {
          label: selectedOptions[2].label,
          value: selectedOptions[2].value,
        };
      }
      console.log("this.text", this.text);
      console.log(this.provinceItem);
      console.log(this.districtItem);
      console.log(this.cityItem);
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          var terminalData = {};
          if (this.issmall == false) {
            terminalData = {
              id: this.ModificationData ? this.ModificationData.id : null,
              sncode: values.snCode,
              merchantMemberNo: this.merchantMemberNo,
              address: values.address,
              city: this.cityItem.value,
              cityName: this.cityItem.label,
              province: this.provinceItem.value,
              provinceName: this.provinceItem.label,
              county: this.districtItem.value,
              countyName: this.districtItem.label,
              contactName: values.contactName,
              contactPhone: values.contactPhone,
              // facilityImg: this.terminal.facilityImg,
              otherImg: this.terminal.otherImg,
            };
          } else {
            terminalData = {
              id: this.ModificationData ? this.ModificationData.id : null,
              sncode: values.snCode,
              merchantMemberNo: this.merchantMemberNo,
              address: values.address,
              city: null,
              cityName: null,
              province: null,
              provinceName: null,
              county: null,
              countyName: null,
              contactName: values.contactName,
              contactPhone: values.contactPhone,
              // facilityImg: this.terminal.facilityImg,
              otherImg: this.terminal.otherImg,
            };
          }
          console.log("terminalData", terminalData);
          this.loading = true;
          if (this.ismdf == false) {
            this.$axios.post("/agent/log/terminal/save", terminalData).then(
              (res) => {
                this.loading = false;
                console.log(res.data);
                if (res.data.code == "OK") {
                  this.success = true;
                } else {
                  this.$message.error(res.data.message);
                }
              },
              (err) => {
                this.loading = false;
                this.$message.error(err.message);
              }
            );
          } else {
            this.$axios.post("/agent/log/terminal/update", terminalData).then(
              (res) => {
                this.loading = false;
                console.log(res.data);
                if (res.data.code == "OK") {
                  this.success = true;
                } else {
                  this.$message.error(res.data.message);
                }
              },
              (err) => {
                this.loading = false;
                this.$message.error(err.message);
              }
            );
          }
        }
      });
    },
    getareaData() {
      this.$axios.get("/agent/division/all").then((res) => {
        const result = res.data;
        if (res.data.list) {
          let list = result.list;
          let arr = [];
          let newArr = list.map((item, index, list) => {
            let test = {
              label: item.label,
              value: item.value,
              children: [],
            };
            arr.push(test);
            if (item.children) {
              let children = [];
              for (let i = 0; i < item.children.length; i++) {
                let test2 = {
                  label: item.children[i].label,
                  value: item.children[i].value,
                  children: [],
                };
                children.push(test2);

                if (item.children[i].children) {
                  let child2 = [];
                  for (let a = 0; a < item.children[i].children.length; a++) {
                    let test3 = {
                      label: item.children[i].children[a].label,
                      value: item.children[i].children[a].value,
                    };
                    child2.push(test3);
                  }
                  children[i].children = child2;
                }
              }
              arr[index]["children"] = children;
            }
            return arr;
          });
          // console.log("newArr", newArr);
          this.options = newArr[0];
          this.onlySH(this.options);
        } else {
        }
      });
    },
    onlySH(list) {
      let arr = [];
      let firstData;

      // 第一种
      // list.map((item, index) => {
      //   if (item.value == '2900') {
      //     arr.push(item);
      //   }
      // })
      // this.options2 = arr;
      // console.log("this.options2", this.options2);

      // 第二种
      list.map((item, index) => {
        if (item.value !== "2900") {
          let data = {
            children: item.children,
            value: item.value,
            label: item.label,
            disabled: true,
          };
          arr.push(data);
        } else {
          firstData = item;
        }
      });
      arr.unshift(firstData);
      this.options = arr;
      console.log("this.options2", this.options);
    },
    NameSearch(value) {
      let parameters = {
        merchantName: value,
      };
      this.seloptions = [];
      this.$axios
        .post("/agent/log/terminal/getMerchantMap", parameters)
        .then((res) => {
          console.log(res.data);
          if (res.data.code == "OK") {
            this.seloptions = res.data.data;
          } else {
            this.seloptions = [];
            this.error = res.data.message;
          }
        });
    },
    goterminalQuery() {
      this.$router.push({ name: "商户终端审核查询" });
    },
    getQueryDetail(id) {
      this.$axios.get("/agent/merchant/network/getByMemberNo/" + id).then(
        (res) => {
          console.log(res);
          if (res.data.code == "OK") {
            this.queryDetail = res.data.data;
            setTimeout(() => {
              this.form.setFieldsValue({
                merchantMemberNo: res.data.data.merchantName,
              });
            }, 0);
            this.merchantMemberNo = res.data.data.memberNo;
            console.log("this.queryDetail", this.queryDetail);
          } else {
            this.$message.error(res.data.message);
          }
        },
        (err) => {}
      );
    },
    handleChange1(d) {
      console.log(d.merchantMemberNo);
      this.merchantMemberNo = d.merchantMemberNo;
      this.getQueryDetail(d.merchantMemberNo);
      let type = d.merchantType;
      console.log(type);
      if (type == "small") {
        this.issmall = true;
      } else {
        this.issmall = false;
      }
    },
    handleChange({ file, fileList }) {
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpeg、 png 2种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > this.imageSize) {
        this.$message.error(`上传图片大小应小于${this.imageSize}Mb`);
        return;
      }
      this.fileList = fileList;
      let obj =
        fileList.length > 0
          ? fileList[0]
          : { response: { data: null, code: null } };
      if (obj) {
        if (obj.response) {
          if (obj.response.code == "OK") {
            console.log(obj.response.data);
            this.terminal.facilityImg = obj.response.data;
          } else {
            this.terminal.facilityImg = "";
          }
        }
      }
    },
    handleChange2({ file, fileList }) {
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpeg、 png 2种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > this.imageSize) {
        this.$message.error(`上传图片大小应小于${this.imageSize}Mb`);
        return;
      }
      this.fileList2 = fileList;
      let obj =
        fileList.length > 0
          ? fileList[0]
          : { response: { data: null, code: null } };
      if (obj) {
        if (obj.response) {
          if (obj.response.code == "OK") {
            this.terminal.otherImg = obj.response.data;
          } else {
            this.terminal.otherImg = "";
          }
        }
      }
    },

    handlePreview(file) {
      console.log("file", file);
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    handlePreview2(file) {
      console.log("file", file);
      this.previewImage2 = file.url || file.thumbUrl;
      this.previewVisible2 = true;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    handleCancel2() {
      this.previewVisible2 = false;
    },
    successCancel() {
      this.success = false;
    },
    validateCode(rule, value, callback) {
      if (value && !/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
        this.phone = false;
        callback("您输入的手机号格式有误！");
        return;
      } else {
        if (!value) {
          this.phone = false;
        } else {
          this.phone = true;
          this.phonevalue = value;
        }
        callback();
      }
    },
    snCodeChange(e) {
      console.log(e.target.value);
      let sncode = e.target.value;
      if (!sncode) {
        console.log("sncode不能为空");
        return;
      }
      this.$axios
        .get("/agent/sncode/getBySnCode/" + e.target.value)
        .then((res) => {
          const result = res.data;
          if (result.code === "OK") {
            console.log(result.data);
            if (result.data) {
              this.terminal = result.data;
            }
          } else {
            this.terminal = {};
            this.error = result.message;
          }
        });
      // this.bankCard.accountName = e.target.value;
    },
    DeviceNumberBlur() {
      // console.log('1242344')
      let snCode = this.form.getFieldValue("snCode");
      this.$axios.get("/agent/sncode/getBySnCode/" + snCode).then(
        (res) => {
          console.log("res", res);
          if (res.data.code != "OK") {
            this.$message.error("终端号错误或该终端已被绑定");
            this.form.setFieldsValue({
              snCode: "",
            });
          }
        },
        (err) => {}
      );
    },
    toSame() {
      console.log("1243235");
      if (this.queryDetail.realAddress) {
        setTimeout(() => {
          this.form.setFieldsValue({
            address: this.queryDetail.realAddress,
          });
        }, 0);
      } else {
        this.$message.warning("未查询到当前商户的实际经营地址");
      }
    },
    getFileDownload(value) {
      let data = value;
      api.getFilePath(
        data,
        (res) => {
          console.log(res);
          if (res.code == "OK") {
            const a = document.createElement("a");
            if (value == "add_terminal_ticket") {
              a.download = `增机单`;
            }
            let downloadUrl = "/file/file/download/" + res.data;
            a.href = downloadUrl;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
  },
};
</script>
<style lang="less" scoped>
.width-sty {
  width: 50%;
}

.w-sty {
  width: 80%;
}

.submitButton {
  width: 140px;
}
</style>